﻿using System.Collections.Specialized;
using System.Linq;
using Framework;
using HtmlAgilityPack;
using ScrapySharp.Extensions;

namespace Koala.JiraTool.Core
{
    internal class LoginController : ILoginController
    {
        private readonly IHttpClient _httpClient;
        private readonly GlobalSettings _globalSettings;

        public LoginController(IHttpClient httpClient, GlobalSettings globalSettings)
        {
            _httpClient = httpClient;
            _globalSettings = globalSettings;
        }

        #region Implementation of ILoginController

        public bool IsLogin()
        {
            return !string.IsNullOrWhiteSpace(GetUserName());
        }

        public bool Login(string userName, string password, out string message)
        {
            var html = _httpClient.PostData(_globalSettings.LoginUrl, new NameValueCollection
                {
                    {"os_username", userName},
                    {"os_password",password}
                });
            if (IsLogin())
            {
                message = "登录成功。";
                return true;
            }
            var document = new HtmlDocument();
            document.LoadHtml(html);
            var documentNode = document.DocumentNode;
            var node = documentNode.CssSelect("div.aui-message>p").FirstOrDefault();
            message = node == null ? "未知错误。" : node.InnerText.Replace("\t", "").Replace("\n", "").Trim();
            return false;
        }

        public bool Logout()
        {
            _httpClient.Reset();
            return false;
        }

        public string GetUserName()
        {
            var html = _httpClient.DownloadString(_globalSettings.LoginUrl);
            var document = new HtmlDocument();
            document.LoadHtml(html);
            var documentNode = document.DocumentNode;
            var meta = documentNode.SelectNodes("/html/head/meta[@name='ajs-remote-user-fullname']/@content")[0];
            var name = meta.Attributes["content"].Value;
            return name;
        }

        #endregion Implementation of ILoginController
    }
}